/**
 * 
 */
package com.jolestar.yayaweibotong.service.impl;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.google.gdata.client.douban.DoubanService;
import com.google.gdata.data.douban.UserEntry;
import com.google.gdata.util.ServiceException;
import com.jolestar.yayaweibotong.ServiceType;
import com.jolestar.yayaweibotong.YaYaAccessToken;
import com.jolestar.yayaweibotong.YaYaConstants;
import com.jolestar.yayaweibotong.YaYaRequestToken;
import com.jolestar.yayaweibotong.YayaException;

/**
 * @author jolestar@gmail.com
 * 
 */
public class DoubanOAuthService extends AbstractOAuthService {

	static {
		DoubanService.CLIENT = DoubanStatusService.OAUTH_CLIENT;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.jolestar.yayaweibotong.service.OAuthService#request(javax.servlet
	 * .http.HttpServletRequest)
	 */
	@Override
	public YaYaRequestToken request(HttpServletRequest request) {
		DoubanService doubanService = new DoubanService(YaYaConstants.APP_NAME,
				ServiceType.douban.getApiKey(),
				ServiceType.douban.getApiSecret());
		String url = doubanService.getAuthorizationUrl(this.generateCallback(
				request, ServiceType.douban));
		return new YaYaRequestToken(doubanService.getRequestToken(),
				doubanService.getRequestTokenSecret(), url);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.jolestar.yayaweibotong.service.OAuthService#requestAccessToken(com
	 * .jolestar.yayaweibotong.YaYaRequestToken, java.lang.String)
	 */
	@Override
	public YaYaAccessToken requestAccessToken(YaYaRequestToken requestToken,
			String verifier) {
		DoubanService doubanService = new DoubanService(YaYaConstants.APP_NAME,
				ServiceType.douban.getApiKey(),
				ServiceType.douban.getApiSecret());
		doubanService.setRequestToken(requestToken.getToken());
		doubanService.setRequestTokenSecret(requestToken.getTokenSecret());
		List<String> results = doubanService.getAccessToken();
		UserEntry user;
		try {
			user = doubanService.getAuthorizedUser();
		} catch (Exception e) {
			throw new YayaException(e);
		}
		return new YaYaAccessToken(results.get(0), results.get(1),
				user.getUid(), user.getTitle().getPlainText());
	}

}
